import 'package:flutter/foundation.dart';
import 'package:flutter/services.dart';

import 'serial_port_platform_interface.dart';

/// An implementation of [SerialPortPlatform] that uses method channels.
class MethodChannelSerialPort extends SerialPortPlatform {
  /// The method channel used to interact with the native platform.
  @visibleForTesting
  final methodChannel = const MethodChannel('serial_port');

  /// The event channel used to receive BatteryState changes from the native platform.
  @visibleForTesting
  EventChannel eventChannel =
  const EventChannel('serial_port/event');

  Stream<String>? _onSerialPortDataChanged;

  @override
  Future<String?> getPlatformVersion() async {
    final version = await methodChannel.invokeMethod<String>('getPlatformVersion');
    return version;
  }

  @override
  Future<bool?> start(String device, int baudrate) async{
    final result = await methodChannel.invokeMethod<bool>('start', {
      'device': device,
      'baudrate': baudrate
    });
    return result;
  }

  @override
  Future<void> setLog(bool value) async {
    await methodChannel.invokeMethod<bool>('setLog', value);
  }

  @override
  Future<bool?> close() async{
    final result = await methodChannel.invokeMethod<bool>('close');
    return result;
  }

  /// Fires whenever the serial port data changes.
  @override
  Stream<String> get onSerialPortDataChanged {
    _onSerialPortDataChanged ??= eventChannel
        .receiveBroadcastStream()
        .map((dynamic event) => '$event');
    // only when you need to do the pre-handle (such as parse them to enum)
    return _onSerialPortDataChanged!;
  }
}
